package com.core.reach.oauth2server.service.impl;

import com.core.reach.oauth2server.domain.AuthUserInfo;
import com.core.reach.oauth2server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Mr_zhangmu
 * @version V1.0
 * @description: TODO
 * @date 2020/6/19 16:02
 **/
@Slf4j
@Service("tUserService")
public class UserServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 通过用户名查询数据
        AuthUserInfo userInfo = userService.findByUsername(s);
        if (userInfo == null) {
            throw new BadCredentialsException("User '" + s + "' not found");
        }
        log.info("userInfo:{}", userInfo.toString());
        // 用户角色
        List<? extends GrantedAuthority> authorities = AuthorityUtils
                .commaSeparatedStringToAuthorityList("ROLE_" + userInfo.getRole());
        return new User(s, userInfo.getPassword(), true, true, true, true, authorities);
    }

}
